
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var geocoder;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
  }
  
  function codeAddress(address) {
	    geocoder.geocode( { 'address': address}, function(results, status) {
	      if (status == google.maps.GeocoderStatus.OK) {
	    	  map.setCenter(results[0].geometry.location);
	    	  var marker = new google.maps.Marker({
	    		  map: map,
	    		  position: results[0].geometry.location
	    		  });
	    	  } else {
	    		  alert("Geocode was not successful for the following reason: " + status);
	    		  }
	      });
	    }
  
  function calcRoute(flag) {
    var start = document.getElementById("address_orig").value;
    var end = document.getElementById("address_dest").value;
    if (flag=='0'){
    	codeAddress(start);
    	end='';
    }else{
    	codeAddress(end);
    }
    var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>
</head>
<body onload="initialize()">
<div>
    <input id="address_orig" type="textbox" value="北京 中关村">
    <input type="button" value="start" onclick="calcRoute('0')">
    <input id="address_dest" type="textbox" value="北京 回龙观">
    <input type="button" value="end" onclick="calcRoute('1')">
</div>

<div id="map_canvas" style="top:30px;"></div>
</body>
</html>
